package com.sindvision.cces.http;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Type;

/*
 * @Author liwentao
 * @Description 元数据封装成特定格式的json数据，并对PageHelper中的page进行PageInfo转换
 * @Date 18:18 2018/10/16
 * @Param
 * @return
 **/
public class ApiResultConverter extends FastJsonHttpMessageConverter {

    @Override
    public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        ServletServerHttpResponse response = (ServletServerHttpResponse) outputMessage;
        HttpServletResponse servletResponse = response.getServletResponse();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes()).getRequest();
        String servletPath = request.getServletPath();
        int status = servletResponse.getStatus();
        if (servletPath.contains("swagger") || servletPath.contains("/v2/api-docs")) {
            super.write(o, contentType, outputMessage);
        } else {
            if (status == 200) {
                if (o instanceof ApiResultVO) {
                    super.write(o, contentType, outputMessage);
                } else {
                    super.write(ApiResult.success(o), contentType, outputMessage);
                }
            } else {
                super.write(o, contentType, outputMessage);
            }
        }
    }
}
